import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet, ScrollView, Switch, TouchableOpacity, Alert } from 'react-native';
import axios from 'axios';
import { useNavigation, useRoute } from '@react-navigation/native';
import { get, post } from '../http/http';

const RoomsiteScreen = () => {
  const [data, setData] = useState(null);
  const navigation = useNavigation();
  const route = useRoute();
  const { classroomId } = route.params;

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const response = await get('security/securityStatistical/api/getAppClassroomSiteEquipmentData', {
        classroomId,
      });
      setData(response.data);
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const change = async (e, equ) => {
    try {
      await post('security/equipmentInfo/api/sendInstructions', {
        classroomId,
        isOpen: e,
        equipmentId: equ.equipmentId,
        messageType: 0,
      });
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const activate = async (isOpen) => {
    try {
      await post('security/securityStatistical/api/roomSiteSendInstructions', {
        classroomId,
        isOpen,
      });
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const repairDevice = () => {
    navigation.navigate('DeviceFixScreen', { classroomId });
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.row}>
        <View style={styles.col}>
          <Button title="一键开启" onPress={() => activate(1)} color="#4EB894" />
        </View>
        <View style={styles.col}>
          <Button title="一键关闭" onPress={() => activate(0)} color="#4EB894" />
        </View>
        <View style={styles.col}>
          <Button title="一键报修" onPress={repairDevice} color="#4EB894" />
        </View>
      </View>
      {data && data.siteList && data.siteList.length > 0 && (
        data.siteList.map((site) => (
          <View key={site.siteName} style={styles.section}>
            <Text style={styles.sectionTitle}>{site.siteName}</Text>
            {site.subMap.map((equ) => (
              <View key={equ.equipmentName} style={styles.group}>
                <Text style={styles.groupTitle}>{equ.equipmentName}</Text>
                <View style={styles.groupContent}>
                  <Text style={styles.groupText}>
                    {equ.controlType === 0 ? (equ.isOpen === 1 ? '已占用' : '未占用') : `${equ.rangeVal}${equ.unitName || ''}`}
                  </Text>
                  <Text style={{ color: equ.isOnLine ? '#00FF7E' : 'red', margin: 'auto 10px' }}>
                    ● {equ.isOnLine ? '在线' : '离线'}
                  </Text>
                  {equ.controlType === 0 && (
                    <Switch
                      value={equ.isOpen === 1}
                      onValueChange={(value) => change(value ? 1 : 0, equ)}
                    />
                  )}
                </View>
              </View>
            ))}
          </View>
        ))
      )}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F7F8F8',
    padding: 10,
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 20,
  },
  col: {
    flex: 1,
    marginHorizontal: 5,
  },
  section: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  group: {
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 15,
    marginBottom: 10,
  },
  groupTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  groupContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  groupText: {
    flex: 1,
  },
});

export default RoomsiteScreen;
